package com.weifly.weistock.core.monitor;

import com.weifly.weistock.core.monitor.bo.MessageBO;
import com.weifly.weistock.core.monitor.bo.MonitorStatusBO;
import com.weifly.weistock.core.task.AbstractUpdateService;
import com.weifly.weistock.core.task.UpdateStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 监控服务基类
 *
 * @author weifly
 * @since 2020/12/02
 */
public abstract class AbstractMonitorService {

    protected Logger log = LoggerFactory.getLogger(this.getClass());
    private SimpleDateFormat timeSdf = new SimpleDateFormat("HH:mm:ss");

    protected int status = AbstractUpdateService.STATUS_INIT; // 状态
    protected String date; // 交易日期
    protected String time; // 更新时间
    private List<MessageBO> messageList = new ArrayList<>(); // 日志消息列表

    /**
     * 更新状态信息
     */
    public synchronized void updateStatus(UpdateStatus status) {
        this.status = status.getStatus();
        this.date = status.makeDateString();
        this.time = status.makeTimeString();
    }

    public synchronized MonitorStatusBO getStatus() {
        MonitorStatusBO statusBO = new MonitorStatusBO();
        statusBO.setStatus(this.status);
        statusBO.setDate(this.date);
        statusBO.setTime(this.time);
        return statusBO;
    }

    /**
     * 写入日志消息
     */
    public synchronized void writeMessage(String message) {
        log.info(message);
        MessageBO messageBO = new MessageBO();
        messageBO.setTime(this.timeSdf.format(new Date()));
        messageBO.setMessage(message);
        messageList.add(messageBO);
        if (messageList.size() > 20) {
            messageList.remove(0);
        }
    }

    /**
     * 返回消息集合
     */
    protected synchronized List<MessageBO> collectMessage() {
        return new ArrayList<>(this.messageList);
    }
}
